package cn.tedu.servlet;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Servlet implementation class IPLimitedServlet
 */
public class IPLimitedServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
    private String ipRange=null;
    /**
     * @see HttpServlet#HttpServlet()
     */
    public IPLimitedServlet() {
        super();
        // TODO Auto-generated constructor stub
    }
    
	@Override
	public void init() throws ServletException {
		System.out.println("init()");
		ipRange=this.getInitParameter("ipRange");
		System.out.println(ipRange);
	}

	/**
	 * @see Servlet#init(ServletConfig)
	 */
	public void init(ServletConfig config) throws ServletException {
		System.out.println("init(config)");
		ipRange=config.getInitParameter("ipRange");
		System.out.println(ipRange);
	}

	/**
	 * @see Servlet#destroy()
	 */
	public void destroy() {
		// TODO Auto-generated method stub
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		System.out.println("IPLimitedServlet-->doGet()");
		String[] ips=ipRange.split("-");
		int ip1=Integer.parseInt(ips[0].substring(ips[0].lastIndexOf(".")+1));
		int ip2=Integer.parseInt(ips[1].substring(ips[1].lastIndexOf(".")+1));
		System.out.println(ip1  +"    "+ip2);
		//获取客户端的ip,谁访问服务器,就获取谁的ip地址
		String realIP=request.getRemoteAddr();
		int clientIP=Integer.parseInt(realIP.substring(realIP.lastIndexOf(".")+1));
		System.out.println("realIP:"+realIP);
		if(clientIP>=ip1 && clientIP<=ip2) {
			//IP地址在符合范围内,跳转到login.html
			response.sendRedirect("login.html");
		}else {
			//IP地址不在符合的范围内,则给一个提示
			PrintWriter out=response.getWriter();
			out.append("ip not a range.    your ip:"+realIP);
			out.close();
		}
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(request, response);
	}

}
